//
//  PurumMinigameEnemy.m
//  PurumClothes
//
//  Created by 솔이 박 on 11. 4. 30..
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "PurumMinigameEnemy.h"


@implementation PurumMinigameEnemy

-(void) tick: (NSTimer*) theTimer
{
	[self update];
}

-(void) update
{
	switch(state)
	{
		case EnemyStateType_Run:
		{
			[self move];
		}break;
			
		case EnemyStateType_Appear:
		case EnemyStateType_Dead:
		{
			[self nextState];
		}break;
			
		case EnemyStateType_Disappear:
		{
			[self removeEnemyImage];
		}break;
	}
}

-(void) move
{
	enemyImage.center = CGPointMake(enemyImage.center.x + velocity, enemyImage.center.y);
	
	if(enemyImage.center.x < 0 || enemyImage.center.x > 300)
	{
		state = EnemyStateType_Disappear;
	}
}

-(void) nextState
{
	if(state == EnemyStateType_Disappear)
		return;
	
	state = (EnemyStateType)(state+1);
}

-(void)initialize:(UIView*)view ofEnemyType:(EnemyType)enemyType withStartX:(int)startX withStartY:(int)startY
{
	x = startX;
	y = startY;
	
	velocity = -10;
	
	type = enemyType;
	
	state = EnemyStateType_Appear;
	
	[self buildEnemy:view];
}

-(void) finalize
{
	[super finalize];
}

-(bool) isEnded
{
	if(state == EnemyStateType_Disappear)
	{
		return YES;
	}
	
	return NO;
}

-(NSString*) getEnemyImagePath
{
	switch(type)
	{
		case EnemyType_Red:
		{
			return @"red_enemy.png";
		}
			
		case EnemyType_Yellow:
		{
			return @"yellow_enemy.png";
		}
			
		case EnemyType_Blue:
		{
			return @"blue_enemy.png";
		}
			
	}
	
	return @"";
}

-(void) loadEnemyImage
{
	NSString* path = [self getEnemyImagePath];
	
	UIImage* image = [UIImage imageNamed:path];
	
	enemyImage = [[[UIImageView alloc] initWithImage:image] autorelease];
	
	CGRect frame = enemyImage.frame;
	frame.origin = CGPointMake(x, y);
	
	enemyImage.frame = frame;
}

-(void) addEnemyImage:(UIView *)view
{
	[view addSubview:enemyImage];
}

-(void) removeEnemyImage
{
	if(enemyImage == 0)
		return;
	
	[enemyImage removeFromSuperview];
	enemyImage = 0;
	
	[self release];
	
}

-(void) buildEnemy:(UIView *)view
{
	[self loadEnemyImage];
	[self addEnemyImage:view];

	[self initializeTimer];
}

-(void)initializeTimer
{
	float theInterval = 1.0f/10.0f;
	[NSTimer scheduledTimerWithTimeInterval:theInterval target:self selector:@selector(tick:) userInfo:nil repeats:YES];
}
@end
